import dayjs from 'dayjs'

// 延时器
export const delay = (ms = 300) => {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

// 计算多当天到向后6天的日期写一个函数  dayjs momentjs
export const getRangeDay = (day = 6) => {
  let days = []
  let weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  for (let i = 1; i <= day; i++) {
    let week = ''
    let weekIndex = dayjs().add(i, 'day').format('d') as unknown as number
    if (i == 1) {
      week = '明天'
    } else if (i == 2) {
      week = '后天'
    } else {
      week = weeks[weekIndex]
    }
    let daytime = dayjs().add(i, 'day')
    let daystr = week + daytime.format('MM月DD日')
    days.push({ daytime: daytime.unix(), daystr })
  }
  return days
}

// 指定年份日期
export const getNumToDate = (n = 20, type = 'year'): [dayjs.Dayjs, string] => {
  let timestamp
  if (type === 'year') {
    timestamp = dayjs().add(n, 'year')
  } else {
    timestamp = dayjs().add(n, 'day')
  }
  return [timestamp, timestamp.format('YYYY-MM-DD')]
}

// 写一个判断是否是移动端
export const isMobile = () => {
  const userAgentInfo = navigator.userAgent
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'Mobile']
  return Agents.some(item => userAgentInfo.includes(item))
}

// 判断是否为空对象
export const isEmptyObj = (obj: object) => {
  return Object.keys(obj).length === 0 ? true : false
}

// 返回非空的对象属性
// export const noEmptySearchObject = (obj: any) => {
export const noEmptySearchObject = <T extends object>(obj: T) => {
  // let ret = {}
  let ret = {} as T
  for (let key in obj) {
    // 它当前有值
    if (obj[key]) {
      // (ret as any)[key] = obj[key]
      ret[key] = obj[key]
    }
  }
  return isEmptyObj(ret) ? null : ret
}

// 把对象转成query字符串
export const objToQueryString = (obj: object) => {
  let ret = ''
  for (let key in obj) {
    ret += `&${key}=${(obj as any)[key]}`
  }
  return ret
}
